package run;


import base.*;
import java.io.IOException;
import java.util.ArrayList;

import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.border.Border;

import java.io.File;
import javax.sound.sampled.*;

public class ServerScreen extends JPanel {
	// --------DATA----------
	private SolverGrid gridPlay;
	
	//private int fullTime;
	
	private Clock clock;
	private Timer timer;

	// ---------GUI------------
	private Box vertBox;
	private Box topBox;
        private Box clientBox;

        private Box client1;
        private Box client2;
        private Box client3;
        private Box client4;
        private int score1,score2,score3,score4;
        private Box clientBox_name1;
        private JLabel client_label1 = new JLabel("Team 1",JLabel.CENTER);
        private static JTextPane client_name1 = new JTextPane();
        private Box clientBox_score1;
        private JTextPane client_score1 = new JTextPane();
        private Box clientBox_answer1;
         private static JTextPane client_answer1 = new JTextPane();
       
        private Box clientBox_name2;
        private JLabel client_label2 = new JLabel("Team 2",JLabel.CENTER);
        private static JTextPane client_name2 = new JTextPane();
        private Box clientBox_score2;
        private JTextPane client_score2 = new JTextPane();
        private Box clientBox_answer2;
         private static JTextPane client_answer2 = new JTextPane();

    private Box clientBox_name3;
    private JLabel client_label3 = new JLabel("Team 3",JLabel.CENTER);
        private static JTextPane client_name3 = new JTextPane();
        private Box clientBox_score3;
        private JTextPane client_score3 = new JTextPane();
        private Box clientBox_answer3;
         private static JTextPane client_answer3 = new JTextPane();

         private Box clientBox_name4;
         private JLabel client_label4 = new JLabel("Team 4",JLabel.CENTER);
        private static JTextPane client_name4 = new JTextPane();
        private Box clientBox_score4;
        private JTextPane client_score4 = new JTextPane();
        private Box clientBox_answer4;
         private static JTextPane client_answer4 = new JTextPane();

	private Box bottomBox;
	private Box clueBox;
	private Box timeBox;
	private Box boxButtons;
	//private JLabel timeLabel = new JLabel("     ", new ImageIcon(this.getClass().getResource("/img/clock.png")), JLabel.CENTER);
	private JTextPane clueTextPane = new JTextPane();
	private JTextPane timeTextPane = new JTextPane();
	private JScrollPane scrollPane;

	private JButton btnFinish = new JButton("Finish", new ImageIcon(this.getClass()
			.getResource("/img/finish.png")));
	private JButton btnCheck = new JButton("Check", new ImageIcon(this
			.getClass().getResource("/img/check.png")));


	private Border brdThinGray = BorderFactory.createLineBorder(Color.BLACK, 1);
        private Border brdThickBlue = BorderFactory.createLineBorder(Color.BLUE, 2);
	private static int MARGIN_GAP = 10;
        
        public static void setAnswer1(String s){
            client_answer1.setText(s);
        }
         public static void setName1(String s){
            client_name1.setText(s);
        }

        public static void setAnswer2(String s){
            client_answer2.setText(s);
        }
         public static void setName2(String s){
            client_name2.setText(s);
        }
        public static void setAnswer3(String s){
            client_answer3.setText(s);
        }
         public static void setName3(String s){
            client_name3.setText(s);
        }
        public static void setAnswer4(String s){
            client_answer4.setText(s);
        }
         public static void setName4(String s){
            client_name4.setText(s);
        }
         public static String getName1(){
           return client_name1.getText();
         }
         public static String getName2(){
           return client_name2.getText();
         }
         public static String getName3(){
           return client_name3.getText();
         }
         public static String getName4(){
           return client_name4.getText();
         }

	public ServerScreen(Crossword cw) {
		this.setLayout(new BorderLayout());
		//Crossword cwPlay = cw;
		gridPlay = new SolverGrid(cw);
		displayGrid();
		gridPlay.setCrossword(cw);
		gridPlay.repopulateWords();

		// remove all listeners
		gridPlay.removeListeners();
		gridPlay.removeKeyListener(gridPlay.getKeyListeners()[0]);
		gridPlay.init();
		validate();

		try {
			jbInit();
		} catch (Exception ex) {
			// ex.printStackTrace();
		}
		addListeners();

	}

	private void addListeners() {
		btnFinish.addActionListener(new ButtonListener());
		btnCheck.addActionListener(new ButtonListener());
		ArrayList squares = gridPlay.getSquares();
		for (int i = 0; i < squares.size(); i++) {
			Square s = (Square) squares.get(i);
			s.addMouseListener(new SquareListener());
		}
	}


	private JTextPane createTime() {
		JTextPane temp = new JTextPane();
		clock = new Clock(gridPlay.getCrossword().getMin(), gridPlay
				.getCrossword().getSec());
//		fullTime = clock.getMaxMin() * 60 + clock.getMaxSec();
		temp.setEditable(false);
		StyledDocument doc = temp.getStyledDocument();
		doc = setTimeStyle(doc);
		try {
			doc.insertString(0, "  " + clock.toString(), doc
					.getStyle("special"));
		} catch (Exception e) {
		}
		return temp;
	}

	private StyledDocument setTimeStyle(StyledDocument doc) {
		Style special = doc.addStyle("special", StyleContext
				.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
		StyleConstants.setBold(special, true);
		StyleConstants.setAlignment(special, StyleConstants.ALIGN_CENTER);
		StyleConstants.setFontSize(special, 25);
		return doc;
	}

	private void displayGrid() {
		gridPlay.Build();
		add(gridPlay, BorderLayout.CENTER);
	}


	private void playSound(String filename) {
		try {
			AudioInputStream audioInput = AudioSystem
					.getAudioInputStream(new File(filename));
			Clip buttonClickSound;
			buttonClickSound = AudioSystem.getClip();
			buttonClickSound.open(audioInput);
			buttonClickSound.start();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private void jbInit() throws Exception {
		this.setBackground(new Color(174, 190, 212));

		vertBox = Box.createVerticalBox();
		topBox = Box.createHorizontalBox();
		bottomBox = Box.createHorizontalBox();

		gridPlay.setPreferredSize(new Dimension(500, 500));
                clientBox = Box.createVerticalBox();
                clientBox.setPreferredSize(new Dimension(200, 500));


                client1 = Box.createVerticalBox();

                client1.setPreferredSize(new Dimension(200, 124));
                client1.setBorder(brdThickBlue);

                client2 = Box.createVerticalBox();
                client2.setPreferredSize(new Dimension(200, 124));
                client2.setBorder(brdThickBlue);

                client3 = Box.createVerticalBox();
                client3.setPreferredSize(new Dimension(200, 124));
                client3.setBorder(brdThickBlue);

                client4 = Box.createVerticalBox();
                client4.setPreferredSize(new Dimension(200, 124));
                client4.setBorder(brdThickBlue);

                client_label1.setFont(new Font("Arial", Font.CENTER_BASELINE, 15));
                client_label2.setFont(new Font("Arial", Font.CENTER_BASELINE, 15));
                client_label3.setFont(new Font("Arial", Font.CENTER_BASELINE, 15));
                client_label4.setFont(new Font("Arial", Font.CENTER_BASELINE, 15));
                
                clientBox_name1 = Box.createVerticalBox();
                clientBox_score1 = Box.createVerticalBox();
                clientBox_answer1 = Box.createVerticalBox();

                clientBox_name2 = Box.createVerticalBox();
                clientBox_score2 = Box.createVerticalBox();
                clientBox_answer2 = Box.createVerticalBox();

                clientBox_name3 = Box.createVerticalBox();
                clientBox_score3 = Box.createVerticalBox();
                clientBox_answer3 = Box.createVerticalBox();

                clientBox_name4 = Box.createVerticalBox();
                clientBox_score4 = Box.createVerticalBox();
                clientBox_answer4 = Box.createVerticalBox();

		clueBox = Box.createHorizontalBox();
		clueBox.setPreferredSize(new Dimension(520, 80));

		timeBox = Box.createHorizontalBox();
		timeBox.setPreferredSize(new Dimension(200, 80));
                timeBox.setBorder(brdThinGray);

		clueTextPane.setBorder(brdThinGray);
		clueTextPane.setEditable(false);
		clueTextPane.setFont(new Font("Arial", Font.CENTER_BASELINE, 15));
		clueTextPane.setText(gridPlay.getThemeName(gridPlay.getCrossword()));
		scrollPane = new JScrollPane(clueTextPane);

		timeTextPane = createTime();
		timeTextPane.setBackground(new Color(174, 190, 212));


		boxButtons = Box.createHorizontalBox();
		boxButtons.setBackground(new Color(199, 223, 236));

                btnFinish.setMaximumSize(new Dimension(110, 38));
		btnFinish.setPreferredSize(new Dimension(110, 38));

		btnCheck.setMaximumSize(new Dimension(110, 38));
		btnCheck.setPreferredSize(new Dimension(110, 38));



		topBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		topBox.add(gridPlay);
		topBox.add(Box.createHorizontalStrut(MARGIN_GAP));
                topBox.add(clientBox);
                clientBox.add(client1);
                    client1.add(client_label1);
                    client1.add(clientBox_name1);
                        clientBox_name1.setBorder(brdThinGray);
                        clientBox_name1.add(client_name1);
                    client1.add(clientBox_score1);
                        clientBox_score1.setBorder(brdThinGray);
                        clientBox_score1.add(client_score1);
                    client1.add(clientBox_answer1);
                        clientBox_answer1.add(client_answer1);
                        clientBox_answer1.setBorder(brdThinGray);
                    client1.add(Box.createHorizontalStrut(MARGIN_GAP));
                clientBox.add(client2);
                     client2.add(client_label2);
                    client2.add(clientBox_name2);
                        clientBox_name2.setBorder(brdThinGray);
                        clientBox_name2.add(client_name2);
                    client2.add(clientBox_score2);
                        clientBox_score2.setBorder(brdThinGray);
                        clientBox_score2.add(client_score2);
                    client2.add(clientBox_answer2);
                        clientBox_answer2.add(client_answer2);
                        clientBox_answer2.setBorder(brdThinGray);
                    client2.add(Box.createHorizontalStrut(MARGIN_GAP));
                clientBox.add(client3);
                    client3.add(client_label3);
                    client3.add(clientBox_name3);
                        clientBox_name3.setBorder(brdThinGray);
                        clientBox_name3.add(client_name3);
                    client3.add(clientBox_score3);
                        clientBox_score3.setBorder(brdThinGray);
                        clientBox_score3.add(client_score3);
                    client3.add(clientBox_answer3);
                        clientBox_answer3.add(client_answer3);
                        clientBox_answer3.setBorder(brdThinGray);
                    client3.add(Box.createHorizontalStrut(MARGIN_GAP));
                clientBox.add(client4);
                     client4.add(client_label4);
                    client4.add(clientBox_name4);
                        clientBox_name4.setBorder(brdThinGray);
                        clientBox_name4.add(client_name4);
                    client4.add(clientBox_score4);
                        clientBox_score4.setBorder(brdThinGray);
                        clientBox_score4.add(client_score4);
                    client4.add(clientBox_answer4);
                        clientBox_answer4.add(client_answer4);
                        clientBox_answer4.setBorder(brdThinGray);
                    client4.add(Box.createHorizontalStrut(MARGIN_GAP));
                  

		bottomBox.add(clueBox);
		clueBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		clueBox.add(scrollPane);
		clueBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		bottomBox.add(timeBox);
		//timeBox.add(timeLabel, CENTER_ALIGNMENT);
		timeBox.add(timeTextPane);

		timeBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		vertBox.add(topBox);
		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		vertBox.add(bottomBox);
		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		vertBox.add(boxButtons);
                boxButtons.add(Box.createHorizontalStrut(MARGIN_GAP));
		boxButtons.add(btnFinish);
		boxButtons.add(Box.createHorizontalStrut(MARGIN_GAP));
		boxButtons.add(btnCheck);


		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		add(vertBox, BorderLayout.CENTER);

		TimeListener t = new TimeListener();
		timer = new Timer(1000, t);
		timer.start();

	}

	class TimeListener implements ActionListener {

		StyledDocument doc = timeTextPane.getStyledDocument();

		public void actionPerformed(ActionEvent e) {
			try {
				if (clock.getMin() == 0 && clock.getSec() == 0) {
					timer.stop();
					playSound("sound/time.wav");
					JOptionPane.showMessageDialog(topBox,"GAME OVER","Time up",JOptionPane.INFORMATION_MESSAGE,new ImageIcon(this.getClass().getResource("/img/time.png")));
				} else {
					doc.remove(0, doc.getLength());
					doc.insertString(0, "  " + clock.decrease().toString(), doc
							.getStyle("special"));
				}
			} catch (Exception m) {};
		}
	}

	class ButtonListener implements ActionListener {
		@SuppressWarnings("empty-statement")
		public void actionPerformed(ActionEvent e) {
			try {
				if (e.getSource() == btnCheck) {
                                  playSound("sound/hint.wav");
                                  gridPlay.hintWord();
                                  if (gridPlay.checkClientIsCorect(client_answer1.getText())){
                                      if(gridPlay.getSelectedWord() == gridPlay.getKey())
                                        score1+=100;
                                      else score1+=10;
                                  client_score1.setText("  "+score1);
                                  }
                                  if (gridPlay.checkClientIsCorect(client_answer2.getText())){
                                      if(gridPlay.getSelectedWord() == gridPlay.getKey())
                                        score2+=100;
                                      else score2+=10;
                                  client_score2.setText("  "+score2);
                                  }
                                  if (gridPlay.checkClientIsCorect(client_answer3.getText())){
                                      if(gridPlay.getSelectedWord() == gridPlay.getKey())
                                        score3+=100;
                                      else score3+=10;
                                  client_score3.setText("  "+score3);
                                  }
                                  if (gridPlay.checkClientIsCorect(client_answer4.getText())){
                                      if(gridPlay.getSelectedWord() == gridPlay.getKey())
                                        score4+=100;
                                      else score4+=10;
                                  client_score4.setText("  "+score4);
                                  }


				} else if (e.getSource() == btnFinish) {

				}


			} catch (Exception m) {};
		}
	}

	class SquareListener implements MouseListener {
		public void mouseClicked(MouseEvent e) {
			Square sq = (Square) e.getSource();
                       gridPlay.setSelectedWord(sq.getWord());
			if (sq.getBackground() == Color.BLACK)
			   clueTextPane.setText(gridPlay.getThemeName(gridPlay.getCrossword()));
                        else if (gridPlay.getSelectedWord() == gridPlay.getKey())
                            clueTextPane.setText("Nếu trả lời sai ô hàng dọc bạn sẽ bị loại khỏi cuộc chơi !");
			else {
                                String s1 = gridPlay.getSelectedClue1();
                                clueTextPane.setText(s1);
                                gridPlay.setClueUsed(1);
                            
				validate();
		       }

             }

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
		}

		public void mouseReleased(MouseEvent e) {
		}

	}
}
